package com.example.woke;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.woke.method.MyApp;
import com.zhongcai.online.R;

import java.util.Hashtable;

import cn.wosai.upay.OrderInfo;
import cn.wosai.upay.PayMethod;
import cn.wosai.upay.UpayCallBack;
import cn.wosai.upay.UpayException;
import cn.wosai.upay.UpayResult;
import cn.wosai.upay.UpayTask;

public class AlipapapayActivity extends Activity implements Callback {

	private float money, stringmionu;
	private String order_id;
	private Handler mHandler;
	private ImageView mImageView;
	private int intExtra;
	private TextView mTtile;
	private TextView mTmoye;
	private MyApp myapp;
	private int screenHigth, screenWidth;
	private RelativeLayout mBar;
//	private String zcaierwei ;//�вƶ�ά��

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView (R.layout.activity_alipapapay);

		Intent intent = getIntent ();
		money = intent.getFloatExtra ("money", 0.01f);
		Log.e("onCreate",money+"");
		intExtra = intent.getIntExtra ("threetyse", 0);
		stringmionu = money * 100;
		order_id = intent.getStringExtra ("order_id");
		myapp = (MyApp) getApplication ();
		screenHigth = myapp.screenHigth;
		screenWidth = myapp.screenWidth;
		intview ();

	}

	private OrderInfo preData() {
		OrderInfo order = new OrderInfo ();
		try {
			order.setAppId ("1001200200000100");
			order.setMerchantId ("00000011001200200000100");
			order.setAppKey ("8501d1f1b8abc824487c8dd029d77639");
			order.setAmount ((long) stringmionu);//�տ����λΪ�� ����Ϊ1��
			order.setOrderId (order_id);//�̻��Լ��Ķ�����
			order.setOperator ("1");//����Ա
			order.setCurType ("156");//���Ҵ��룬Ĭ��Ϊ156
			order.setRemark ("中财收款");//���ױ�ע
			order.setSubject ("中财收款");//��Ʒ���
//		    	order.setNotifyUrl("http://test.iwoker.cn/api/order/doOrder");//���Իص���ַ
			order.setNotifyUrl ("http://app.88china.com:8384/api/order/doOrder");//�вƻص���ַ
//		    	order.setNotifyUrl(Contants.BASEURL+"/api/order/doorder");//�ص���ַ
//		    	order.setModel(OrderInfo.PayModel.NO_UI);//�޽���ģʽ


		} catch (UpayException e) {
			e.printStackTrace ();
			Toast.makeText (AlipapapayActivity.this, "设置OrderInfo参数失败！",
					Toast.LENGTH_SHORT).show ();
		}
		return order;
	}

	/**
	 * @param url
	 * @param width
	 * @param height
	 * @return
	 */
	public Bitmap createQRImage(String url, final int width, final int height) {
		try {
			// �ж�URL�Ϸ���
			if (url == null || "".equals (url) || url.length () < 1) {
				return null;
			}
			Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String> ();
			hints.put (EncodeHintType.CHARACTER_SET, "utf-8");
			// ͼ�����ת����ʹ���˾���ת��
			BitMatrix bitMatrix = new QRCodeWriter ().encode (url,
					BarcodeFormat.QR_CODE, width, height, hints);
			int[] pixels = new int[width * height];
			// �������ﰴ�ն�ά����㷨�������ɶ�ά���ͼƬ��
			// ����forѭ����ͼƬ����ɨ��Ľ��
			for (int y = 0; y < height; y++) {
				for (int x = 0; x < width; x++) {
					if (bitMatrix.get (x, y)) {
						pixels[y * width + x] = 0xff000000;
					} else {
						pixels[y * width + x] = 0xffffffff;
					}
				}
			}
			// ��ɶ�ά��ͼƬ�ĸ�ʽ��ʹ��ARGB_8888
			Bitmap bitmap = Bitmap.createBitmap (width, height,
					Bitmap.Config.ARGB_8888);
			bitmap.setPixels (pixels, 0, width, 0, 0, width, height);
			return bitmap;
		} catch (WriterException e) {
			e.printStackTrace ();
		}
		return null;
	}


	@Override
	public boolean handleMessage(Message msg) {
		// TODO Auto-generated method stub
		if (msg.what == 0x101) {
			String trim = msg.obj.toString ().trim ();//trim��Ҫ������Ϣ
			Bitmap createQRImage = createQRImage (trim, screenWidth / 5 * 4, screenWidth / 5 * 4);//�������ɵķ���
			mImageView.setImageBitmap (createQRImage);
			if (null != createQRImage) {

			} else {

			}
			mBar.setVisibility (View.GONE);
//			Log.e("trim", "trim"+trim);
		}
		return false;
	}

	public class MyRunnable implements Runnable {
		public void run() {
			OrderInfo preData = preData ();
			if (intExtra == 0) {
				preData.setPayMethod (PayMethod.UPAY_ALIPAY);
			} else {
				preData.setPayMethod (PayMethod.UPAY_WEIXIN);
			}
			UpayTask.getInstance ().getPayQrcode (AlipapapayActivity.this, preData,
					new UpayCallBack () {

						private String qrCodeUrl;

						@Override
						public void onExecuteResult(UpayResult arg0) {
							Log.e ("arg0", "77777" + arg0);
//							ArrayList list = new ArrayList(arg0.toString().split(''));
							if (arg0 != null && arg0.getQrCodeUrl () != null) {
								int state = arg0.getState ();
								qrCodeUrl = arg0.getQrCodeUrl ();
								if (state != 0) {
									Toast.makeText (AlipapapayActivity.this, "金额超限", Toast.LENGTH_SHORT)
											.show ();
									finish ();
								} else {
									Message msg = mHandler.obtainMessage ();
									msg.what = 0x101;
									msg.obj = qrCodeUrl;
									mHandler.sendMessage (msg);
								}
//								Log.e("state", "state"+state);
							}
						}
					});
		}
	}

	private void intview() {
		mTmoye = (TextView) findViewById (R.id.avpay_text_monye);
		mTtile = (TextView) findViewById (R.id.avsqb_title_text);
		mBar = (RelativeLayout) findViewById (R.id.avalipay_frame);
		mBar.setVisibility (View.VISIBLE);
		TextView mTtype = (TextView) findViewById (R.id.avpay_text_therrtype);
		if (intExtra == 1) {
			mTtile.setText ("微信收款");
			mTtype.setText ("微信扫一扫，向我付款");
		} else if (intExtra == 3) {
			mTtile.setText (getResources().getString(R.string.oem_ewm_shao_title));
			mTtype.setText (getResources().getString(R.string.oem_ewm_shao));
		}
		mTmoye.setText ("￥" + money);
		mHandler = new Handler (AlipapapayActivity.this);
		mImageView = (ImageView) findViewById (R.id.avpay_image_code);
		LayoutParams params = mImageView.getLayoutParams ();
		params.width = screenWidth / 5 * 4;
		params.height = screenWidth / 5 * 4;
		mImageView.setLayoutParams (params);
		findViewById (R.id.avsqb_image_back).setOnClickListener (new OnClickListener () {

			@Override
			public void onClick(View v) {
				finish ();
			}
		});
		if (intExtra == 3) {
			String zcerweima = "";
//			ArrayList<String> list = new ArrayList<String>();
//			HashMap<String, String> map = new HashMap<String, String>();
//			map.put("order_id", order_id);
//			map.put("money", ""+money);
//			map.put("userid", ""+myap.getuser_id());
//			zcaierwei = order_id + "I"+myap.getuser_id()+"D"+money;
			zcerweima = order_id + "," + money + "," + myapp.getDatas_load ()
					.getId () + "," + "ZC16";
//			list.add(order_id);
//			list.add(""+money);
//			list.add(myap.getuser_id());
//			list.add("ZC16");
//			Log.e("list", "list"+list);
			Message msg = mHandler.obtainMessage ();
			msg.what = 0x101;
			msg.obj = zcerweima;
			mHandler.sendMessage (msg);
		} else {
			Thread t = new Thread (new MyRunnable ());//����ȵ�һ�ִ����̶߳�����˸��������
			t.start ();
		}

	}
}
